import { defineStore } from 'pinia';
import { ref, computed } from 'vue'; 
import { invoke } from '@tauri-apps/api/core';
import { getAppSetting, setAppSetting } from '../tauriApi';
import { workspaceIndexer } from '../services/WorkspaceIndexer';

export interface DirEntry {
  name: string;
  path: string;
  isDir?: boolean;
  is_dir?: boolean;
  isFolder?: boolean;
}

// --- 增量刷新用缓存 & 数据结构 ---
export interface TreeNode {
  id: string;
  label: string;
  isDir: boolean;
  children?: TreeNode[];
}

// 缓存结构：路径 -> children 列表
interface TreeCache {
  [dirPath: string]: TreeNode[];
}

export const useWorkspaceStore = defineStore('workspace', () => {
  // 工作区状态
  const workspaceRoot = ref<string>('');
  const selectedPath = ref<string>('');
  const workspaceRefreshTick = ref<number>(0);

  // 缓存：已展开目录的children，避免重复读取
  const treeCache = ref<TreeCache>({});
  
  // 索引构建状态
  const isIndexingEnabled = ref(true);
  const autoStartIndexing = ref(true);

  // 计算属性
  const hasWorkspace = computed(() => !!workspaceRoot.value);
  const currentWorkspace = computed(() => workspaceRoot.value);

  // 统一的路径规范化（仅用于缓存键），避免 Windows 下 \ 与 / 以及盘符大小写/尾随斜杠导致的失效
  function normalizePath(p: string): string {
    let s = String(p || '').replace(/\\/g, '/');
    // 去掉尾随斜杠（保留根路径如 "C:/" 的情况）
    if (s.length > 3) s = s.replace(/\/+$/g, '');
    // Windows: 盘符存在时统一小写，避免大小写不一致导致缓存键不一致
    if (/^[a-zA-Z]:\//.test(s)) s = s.toLowerCase();
    return s;
  }

  // 纯计算逻辑：文件系统读取封装
  async function readDir(path: string): Promise<DirEntry[]> {
    try {
      const entries = await invoke<DirEntry[]>('fs_read_dir', { path });
      return Array.isArray(entries) ? entries : [];
    } catch {
      return [];
    }
  }

  async function readText(path: string): Promise<string> {
    try {
      return await invoke<string>('fs_read_text', { path });
    } catch {
      return '';
    }
  }

  // --- 增量刷新相关 ---
  // 从缓存或实际文件系统读取目录
  async function getCachedChildren(dirPath: string, forceReload = false): Promise<TreeNode[]> {
    const key = normalizePath(dirPath);
    
    // 优先使用预构建索引
    if (isIndexingEnabled.value && !forceReload) {
      try {
        const indexedChildren = workspaceIndexer.getIndexedChildren(dirPath);
        if (indexedChildren !== null) {
          // 同时更新内存缓存以保持一致性
          treeCache.value[key] = indexedChildren;
          return indexedChildren;
        }
      } catch (error) {
        console.warn('Failed to access indexed children, falling back to cache/reload:', error);
      }
    }
    
    // 如果强制重新加载或缓存不存在，则重新加载
    if (forceReload || !treeCache.value[key]) {
      return await reloadChildren(dirPath);
    }
    
    // 返回缓存的结果
    return treeCache.value[key];
  }

  // 重新加载目录内容并更新缓存
  async function reloadChildren(dirPath: string): Promise<TreeNode[]> {
    const key = normalizePath(dirPath);
    const entries = await readDir(dirPath);
    const children = entries.map(it => ({
      id: it.path,
      label: it.name,
      isDir: !!(it.is_dir || it.isDir || it.isFolder),
    }));
    treeCache.value[key] = children;
    return children;
  }

  // 增量刷新：根据文件系统事件精确更新特定目录
  function invalidateDir(dirPath: string) {
    const key = normalizePath(dirPath);
    delete treeCache.value[key];
  }

  // 重新验证目录内容，如果发现问题则强制重新加载
  async function revalidateDirectory(dirPath: string): Promise<TreeNode[]> {
    try {
      const key = normalizePath(dirPath);
      const cached = treeCache.value[key];
      
      // 检查缓存是否存在且有效
      if (!cached) {
        return await reloadChildren(dirPath);
      }
      
      // 对于存在的缓存，进行简单验证
      // 如果缓存为空数组但实际可能有内容，则重新加载
      if (cached.length === 0) {
        // 可以在这里添加更智能的检查逻辑
        // 比如检查文件系统最后修改时间等
        return await reloadChildren(dirPath);
      }
      
      return cached;
    } catch (error) {
      console.warn('Failed to revalidate directory:', dirPath, error);
      return await reloadChildren(dirPath);
    }
  }

  // 根据文件事件增量刷新
  function applyFileChange(eventType: string, filePath: string, oldPath?: string) {
    const parentPath = getParentPath(filePath);
    const oldParentPath = oldPath ? getParentPath(oldPath) : null;

    switch (eventType) {
      case 'create':
      case 'delete':
        if (parentPath) {
          invalidateDir(parentPath);
          // 同时更新索引
          if (isIndexingEnabled.value) {
            void refreshDirectoryIndex(parentPath);
          }
        }
        break;
      case 'rename':
        if (parentPath) {
          invalidateDir(parentPath);
          if (isIndexingEnabled.value) {
            void refreshDirectoryIndex(parentPath);
          }
        }
        if (oldParentPath && oldParentPath !== parentPath) {
          invalidateDir(oldParentPath);
          if (isIndexingEnabled.value) {
            void refreshDirectoryIndex(oldParentPath);
          }
        }
        break;
      case 'modify':
        // 文件内容修改通常不影响目录树结构，但可能有meta改变
        if (parentPath) {
          invalidateDir(parentPath);
          // 对于修改事件，通常不需要更新目录索引
        }
        break;
    }
  }

  // 获取路径的父目录
  function getParentPath(filePath: string): string | null {
    if (!filePath) return null;
    const normalized = normalizePath(filePath);
    const lastSlash = normalized.lastIndexOf('/');
    return lastSlash > 0 ? normalized.substring(0, lastSlash) : null;
  }

  // 索引管理功能
  async function startWorkspaceIndexing(options?: {
    maxDepth?: number;
    excludePatterns?: string[];
  }): Promise<boolean> {
    const root = workspaceRoot.value;
    if (!root) {
      console.warn('Cannot start indexing: workspace root is not set');
      return false;
    }
    
    // 默认排除模式
    const defaultExcludePatterns = [
      'node_modules',
      '.git',
      '.svn',
      '.hg',
      'target',
      'build',
      'dist',
      'out',
      '*.log',
      '.DS_Store',
      'Thumbs.db'
    ];
    
    const indexingOptions = {
      maxDepth: options?.maxDepth || 8,
      excludePatterns: [...defaultExcludePatterns, ...(options?.excludePatterns || [])]
    };
    
    return await workspaceIndexer.buildIndex(root, indexingOptions);
  }
  
  function stopWorkspaceIndexing(): void {
    workspaceIndexer.cancelIndexing();
  }
  
  function clearWorkspaceIndex(): void {
    workspaceIndexer.clearIndex();
    // 也清空内存缓存
    treeCache.value = {};
  }
  
  function isDirectoryIndexed(dirPath: string): boolean {
    return workspaceIndexer.isDirectoryIndexed(dirPath);
  }
  
  async function refreshDirectoryIndex(dirPath: string): Promise<void> {
    await workspaceIndexer.updateDirectoryIndex(dirPath);
    // 同时清空相关的内存缓存
    const key = normalizePath(dirPath);
    delete treeCache.value[key];
  }

  // 状态管理 actions
  async function setWorkspaceRoot(path: string) {
    const oldRoot = workspaceRoot.value;
    workspaceRoot.value = String(path || '');
    
    // 清空缓存和索引
    treeCache.value = {};
    
    if (oldRoot !== workspaceRoot.value) {
      // 工作区根路径发生变化，清空旧索引
      clearWorkspaceIndex();
      
      // 自动启动新的索引构建
      if (autoStartIndexing.value && workspaceRoot.value) {
        // 延迟启动，让 UI 有时间更新
        setTimeout(() => {
          void startWorkspaceIndexing();
        }, 1000);
      }
    }
    
    try {
      await setAppSetting('workspaceRoot', workspaceRoot.value);
    } catch (error) {
      console.warn('Failed to save workspace root to settings:', error);
    }
  }

  function setSelectedPath(path: string) {
    selectedPath.value = String(path || '');
  }

  function refreshWorkspace() {
    workspaceRefreshTick.value++;
  }

  // 全量刷新：清除所有缓存
  function forceRefreshTree() {
    treeCache.value = {};
    // 同时清空索引，强制重新构建
    if (isIndexingEnabled.value) {
      clearWorkspaceIndex();
      if (workspaceRoot.value) {
        setTimeout(() => {
          void startWorkspaceIndexing();
        }, 500);
      }
    }
    refreshWorkspace();
  }

  // 从设置中恢复工作区根目录
  async function loadWorkspaceFromSettings() {
    try {
      const saved = await getAppSetting('workspaceRoot');
      if (saved) {
        workspaceRoot.value = String(saved);
        
        // 自动启动索引构建
        if (autoStartIndexing.value) {
          setTimeout(() => {
            void startWorkspaceIndexing();
          }, 2000); // 稍微延迟，让应用完全加载
        }
      }
    } catch (error) {
      console.warn('Failed to load workspace root from settings:', error);
    }
  }

  return {
    // 状态
    workspaceRoot,
    selectedPath,
    workspaceRefreshTick,
    isIndexingEnabled,
    autoStartIndexing,
    
    // 计算属性
    hasWorkspace,
    currentWorkspace,
    
    // 纯计算/IO 方法
    readDir,
    readText,
    
    // 状态管理
    setWorkspaceRoot,
    setSelectedPath,
    refreshWorkspace,
    loadWorkspaceFromSettings,

    // 增量刷新 API
    getCachedChildren,
    reloadChildren,
    revalidateDirectory,
    invalidateDir,
    applyFileChange,
    forceRefreshTree,
    
    // 索引管理 API
    startWorkspaceIndexing,
    stopWorkspaceIndexing,
    clearWorkspaceIndex,
    isDirectoryIndexed,
    refreshDirectoryIndex,
    
    // 索引器访问（用于状态栏等组件）
    get indexer() { return workspaceIndexer; }
  };
});